#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Vim配置文件处理器

提供Vim配置文件的语法识别和高亮规则
"""

import re
from typing import Dict, List, Any

from .base import LanguageHandler


class VimHandler(LanguageHandler):
    """
    Vim配置文件处理器

    提供Vim配置文件的语法识别和高亮规则
    """

    # Vim配置文件扩展名和特殊文件名
    file_extensions = [
        ".vim",
        ".vimrc",
        "_vimrc",
        "vimrc",
        ".gvimrc",
        "_gvimrc",
        "gvimrc",
    ]

    @classmethod
    def get_language_name(cls) -> str:
        """
        获取语言处理器名称

        Returns:
            str: 语言处理器名称"vim"
        """
        return "vim"

    def _setup_language(self):
        """设置Vim配置文件的语法规则"""
        # Vim命令和选项
        self._keywords = [
            # 基本命令
            "set",
            "let",
            "function",
            "endfunction",
            "if",
            "endif",
            "else",
            "elseif",
            "while",
            "endwhile",
            "for",
            "endfor",
            "try",
            "catch",
            "endtry",
            "finally",
            "execute",
            "echo",
            "echomsg",
            "echoerr",
            "finish",
            "return",
            # 选项
            "autoindent",
            "autoread",
            "autowrite",
            "autowriteall",
            "backup",
            "backupdir",
            "backupcopy",
            "backupext",
            "backupskip",
            "binary",
            "bomb",
            "buflisted",
            "bufhidden",
            "buftype",
            "casemap",
            "cdpath",
            "cedit",
            "charconvert",
            "cinkeys",
            "cinoptions",
            "cinwords",
            "clipboard",
            "cmdheight",
            "cmdwinheight",
            "colorcolumn",
            "columns",
            "comments",
            "commentstring",
            "compatible",
            "complete",
            "completefunc",
            "completeopt",
            "concealcursor",
            "conceallevel",
            "confirm",
            "cpoptions",
            "cryptmethod",
            "cscopeprg",
            "cscopequickfix",
            "cscopetag",
            "cscopetagorder",
            "cscopeverbose",
            "cursorcolumn",
            "cursorline",
            "debug",
            "define",
            "delcombine",
            "dictionary",
            "diff",
            "diffexpr",
            "diffopt",
            "digraph",
            "directory",
            "display",
            "eadirection",
            "encoding",
            "endofline",
            "equalalways",
            "equalprg",
            "errorbells",
            "errorfile",
            "errorformat",
            "esckeys",
            "eventignore",
            "expandtab",
            "exrc",
            "fileencoding",
            "fileencodings",
            "fileformat",
            "fileformats",
            "fileignorecase",
            "filetype",
            "fillchars",
            "fixendofline",
            "foldclose",
            "foldcolumn",
            "foldenable",
            "foldexpr",
            "foldignore",
            "foldlevel",
            "foldlevelstart",
            "foldmarker",
            "foldmethod",
            "foldminlines",
            "foldnestmax",
            "foldopen",
            "foldtext",
            "formatexpr",
            "formatlistpat",
            "formatoptions",
            "formatprg",
            "fsync",
            "gdefault",
            "grepformat",
            "grepprg",
            "guicursor",
            "guiheadroom",
            "guifont",
            "guifontset",
            "guifontwide",
            "guioptions",
            "guipty",
            "guitablabel",
            "guitabtooltip",
            "helpfile",
            "helpheight",
            "helplang",
            "hidden",
            "history",
            "hlsearch",
            "icon",
            "iconstring",
            "ignorecase",
            "imactivatefunc",
            "imcmdline",
            "imdisable",
            "iminsert",
            "imsearch",
            "include",
            "includeexpr",
            "incsearch",
            "indentexpr",
            "indentkeys",
            "inex",
            "infercase",
            "insertmode",
            "isfname",
            "isident",
            "iskeyword",
            "isprint",
            "joinspaces",
            "key",
            "keymap",
            "keymodel",
            "keywordprg",
            "langmap",
            "langmenu",
            "laststatus",
            "lazyredraw",
            "linebreak",
            "lines",
            "linespace",
            "lisp",
            "lispwords",
            "list",
            "listchars",
            "loadplugins",
            "magic",
            "makeef",
            "makeprg",
            "matchpairs",
            "matchtime",
            "maxcombine",
            "maxfuncdepth",
            "maxmapdepth",
            "maxmem",
            "maxmempattern",
            "maxmemtot",
            "menuitems",
            "mkspellmem",
            "modeline",
            "modelineexpr",
            "modelines",
            "modifiable",
            "modified",
            "more",
            "mouse",
            "mousef",
            "mousefocus",
            "mousehide",
            "mousemodel",
            "mouseshape",
            "mousetime",
            "mousescroll",
            "nrformats",
            "number",
            "numberwidth",
            "omnifunc",
            "operatorfunc",
            "osfiletype",
            "paragraphs",
            "paste",
            "pastetoggle",
            "patchexpr",
            "patchmode",
            "path",
            "preserveindent",
            "previewheight",
            "previewwindow",
            "printdevice",
            "printencoding",
            "printexpr",
            "printfont",
            "printheader",
            "printoptions",
            "prompt",
            "pumheight",
            "quoteescape",
            "readonly",
            "remap",
            "report",
            "restorescreen",
            "revins",
            "rightleft",
            "rightleftcmd",
            "runtimepath",
            "ruler",
            "rulerformat",
            "scroll",
            "scrollbind",
            "scrolljump",
            "scrolloff",
            "scrollopt",
            "sections",
            "secure",
            "selection",
            "selectmode",
            "sessionoptions",
            "shell",
            "shellcmdflag",
            "shellpipe",
            "shellquote",
            "shellredir",
            "shellslash",
            "shelltemp",
            "shelltype",
            "shellxquote",
            "shiftround",
            "shiftwidth",
            "shortmess",
            "shortname",
            "showbreak",
            "showcmd",
            "showfulltag",
            "showmatch",
            "showmode",
            "showtabline",
            "sidescroll",
            "sidescrolloff",
            "signcolumn",
            "smartcase",
            "smartindent",
            "smarttab",
            "softtabstop",
            "spell",
            "spellcapcheck",
            "spellfile",
            "spelllang",
            "spelloptions",
            "spellsuggest",
            "splitbelow",
            "splitright",
            "startofline",
            "statusline",
            "suffixes",
            "suffixesadd",
            "swapfile",
            "swapname",
            "switchbuf",
            "synmaxcol",
            "syntax",
            "tabline",
            "tabpagemax",
            "tabstop",
            "tagbsearch",
            "taglength",
            "tagrelative",
            "tags",
            "tagstack",
            "term",
            "termbidi",
            "termencoding",
            "termguicolors",
            "termpastefilter",
            "termsize",
            "textauto",
            "textmode",
            "textwidth",
            "thesaurus",
            "tildeop",
            "timeout",
            "timeoutlen",
            "title",
            "titlelen",
            "titleold",
            "titlestring",
            "ttimeout",
            "ttimeoutlen",
            "ttybuiltin",
            "ttyfast",
            "ttymouse",
            "ttyscroll",
            "ttytype",
            "undodir",
            "undofile",
            "undolevels",
            "undoreload",
            "updatecount",
            "updatetime",
            "verbose",
            "verbosefile",
            "viewdir",
            "viewoptions",
            "viminfo",
            "virtualedit",
            "visualbell",
            "warn",
            "wildchar",
            "wildcharm",
            "wildignore",
            "wildignorecase",
            "wildmenu",
            "wildmode",
            "wildoptions",
            "winaltkeys",
            "window",
            "winheight",
            "winfixheight",
            "winfixwidth",
            "winminheight",
            "winminwidth",
            "winpty",
            "winaltkeys",
            "wrap",
            "wrapmargin",
            "wrapscan",
            "write",
            "writeany",
            "writebackup",
            # 映射命令
            "map",
            "noremap",
            "nnoremap",
            "vnoremap",
            "inoremap",
            "cnoremap",
            "onoremap",
            "snoremap",
            "xnoremap",
            "map!",
            "noremap!",
            "lmap",
            "lnoremap",
            "nmap",
            "vmap",
            "xmap",
            "smap",
            "omap",
            "cmap",
            "imap",
            "tmap",
            # 自动命令
            "autocmd",
            "augroup",
            "au",
            # 高亮
            "highlight",
            "hi",
            "highlight clear",
            "hi clear",
            # 颜色方案
            "colorscheme",
            "color",
            # 函数
            "function",
            "func",
            "endfunction",
            "endfu",
            "return",
            # 变量
            "let",
            "unlet",
            "lockvar",
            "unlockvar",
            "const",
            # 条件和循环
            "if",
            "else",
            "elseif",
            "endif",
            "while",
            "endwhile",
            "for",
            "endfor",
            "try",
            "catch",
            "endtry",
            "finally",
            "throw",
            # 执行
            "execute",
            "eval",
            "call",
            "source",
            "runtime",
            "finish",
            # 输出
            "echo",
            "echomsg",
            "echoerr",
            "echon",
            "echom",
            "echoe",
            # 其他
            "normal",
            "silent",
            "verbose",
            "debug",
            "scriptnames",
            "version",
            "intro",
            "registers",
            "marks",
            "jumps",
            "changes",
            "undolist",
            "history",
            "ls",
            "files",
            "buffers",
            "tabs",
            "windows",
            "args",
            "oldfiles",
            "cquit",
            "quit",
            "wq",
            "wqall",
            "xall",
            "xit",
            "exit",
            "close",
            "hide",
            "stop",
            "suspend",
            "shell",
            "mksession",
            "mkview",
            "loadview",
            "mkvimrc",
            "vimrc",
        ]

        # 正则表达式模式
        self._regex_patterns = {
            # 单引号字符串
            "single_strings": r"'(?:[^'\\]|\\.)*'",
            # 注释 - 以"开头，但前面可以有空白字符，且前面不能有转义字符
            # 支持行首注释和行内注释
            "comments": r'(?<!\\)(?:^\s*".*$|\s+"[^"]*$)',
            # 关键字 - 使用单词边界确保匹配完整单词
            "keywords": r"\b("
            + "|".join(re.escape(k) for k in self._keywords)
            + r")\b",
            # 数字 - 包括整数、浮点数
            "numbers": r"\b\d+(?:\.\d+)?\b",
            # 变量 - 以&开头表示选项，以$开头表示环境变量，以@开头表示寄存器
            "variables": r"[&$@][a-zA-Z_][a-zA-Z0-9_]*|[a-zA-Z_][a-zA-Z0-9_]*:",
            # 函数定义 - function关键字或函数名后的括号
            "functions": r"\bfunction\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(|\b([a-zA-Z_][a-zA-Z0-9_]*)\s*\(",
            # 自动命令 - autocmd或au命令
            "autocmds": r"\b(?:autocmd|au)\b",
            # 映射 - map命令
            "maps": r"\b(?:map|noremap|nnoremap|vnoremap|inoremap|cnoremap|onoremap|snoremap|xnoremap|map!|noremap!|lmap|lnoremap|nmap|vmap|xmap|smap|omap|cmap|imap|tmap)\b",
            # 高亮 - highlight或hi命令
            "highlights": r"\b(?:highlight|hi)\b",
            # 颜色方案 - colorscheme或color命令
            "colorschemes": r"\b(?:colorscheme|color)\b",
            # 键值对 - 选项设置中的=号
            "key_value_pairs": r"([a-zA-Z_][a-zA-Z0-9_]*)\s*=",
            # 布尔值 - on/off, true/false, 1/0
            "booleans": r"\b(?:on|off|true|false|yes|no|1|0)\b",
            # 特殊字符 - 转义序列
            "special_chars": r"\\[nt\"'\\]",
            # 路径 - 文件路径
            "paths": r"(?:[a-zA-Z]:[/\\]|~/|/)[\w/\\.-]*",
            # 正则表达式模式 - /pattern/或'pattern'或"pattern"
            "patterns": r'/(?:[^/\\]|\\/)*/|\'(?:[^\'\\]|\\.)*\'|"(?:[^"\\]|\\.)*"',
            # 行号 - 行号范围
            "line_ranges": r"\d+(?:,\d+)?",
            # 寄存器 - "a, "b等
            "registers": r'"[a-zA-Z0-9.%#:"]',
            # 标记 - 'a, 'b等
            "marks": r"'[a-zA-Z0-9]",
            # 特殊键 - <F1>, <C-x>等
            "special_keys": r"<[A-Za-z][A-Za-z0-9-]*>",
        }

        # 标签样式 - 使用适合Vim配置的配色方案
        self._tag_styles = {
            # 注释 - 绿色
            "comments": {
                "foreground": "#00AA00",
            },
            # 单引号字符串 - 深棕色
            "single_strings": {
                "foreground": "#A0522D",
            },
            # 关键字 - 深蓝色
            "keywords": {
                "foreground": "#000080",
            },
            # 数字 - 深红色
            "numbers": {
                "foreground": "#8B0000",
            },
            # 变量 - 紫色
            "variables": {
                "foreground": "#800080",
            },
            # 函数 - 深紫色
            "functions": {
                "foreground": "#4B0082",
            },
            # 自动命令 - 深青色
            "autocmds": {
                "foreground": "#008B8B",
            },
            # 映射 - 深蓝色
            "maps": {
                "foreground": "#0000CD",
            },
            # 高亮 - 深红色
            "highlights": {
                "foreground": "#8B0000",
            },
            # 颜色方案 - 深绿色
            "colorschemes": {
                "foreground": "#006400",
            },
            # 键值对 - 深蓝色
            "key_value_pairs": {
                "foreground": "#00008B",
            },
            # 布尔值 - 深橙色
            "booleans": {
                "foreground": "#FF8C00",
            },
            # 特殊字符 - 深红色
            "special_chars": {
                "foreground": "#DC143C",
            },
            # 路径 - 深灰色
            "paths": {
                "foreground": "#696969",
            },
            # 正则表达式模式 - 深棕色
            "patterns": {
                "foreground": "#8B4513",
            },
            # 行号 - 深蓝色
            "line_ranges": {
                "foreground": "#0000CD",
            },
            # 寄存器 - 深紫色
            "registers": {
                "foreground": "#4B0082",
            },
            # 标记 - 深绿色
            "marks": {
                "foreground": "#006400",
            },
            # 特殊键 - 深红色
            "special_keys": {
                "foreground": "#8B0000",
            },
        }

        # 自定义模式处理顺序 - 确保字符串和注释有正确的优先级
        self._pattern_order = [
            "single_strings",  # 字符串优先，避免被其他模式覆盖
            "patterns",  # 正则表达式模式（包含字符串）
            "comments",  # 注释次优先
            "keywords",  # Vim关键字
            "functions",  # 函数定义
            "autocmds",  # 自动命令
            "maps",  # 映射命令
            "highlights",  # 高亮命令
            "colorschemes",  # 颜色方案命令
            "variables",  # 变量
            "key_value_pairs",  # 键值对
            "booleans",  # 布尔值
            "numbers",  # 数字
            "special_chars",  # 特殊字符
            "paths",  # 路径
            "line_ranges",  # 行号范围
            "registers",  # 寄存器
            "marks",  # 标记
            "special_keys",  # 特殊键
        ]

    def get_pattern_order(self) -> List[str]:
        """
        获取模式处理顺序

        Returns:
            List[str]: 模式处理顺序列表
        """
        return self._pattern_order
